package cn.ibizlab.odoo.mybatis.util.helper;

import com.baomidou.mybatisplus.annotation.TableId;
import cn.ibizlab.odoo.core.util.helper.DEFieldCacheMap;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.List;

/**
 * 实体辅助类
 */
@Component
public class DEHelper {

    /**
     * 通过实体获取实体主键属性
     * @param entity
     * @return
     */
    public Field getKeyField(Object entity){

        if(ObjectUtils.isEmpty(entity))
            return null;

        DEFieldCacheMap.getFieldMap(entity.getClass().getName());
        Field keyField =null;
        List<Field> fields =  DEFieldCacheMap.getFields(entity.getClass().getName());

        for(Field field:fields){
            TableId deField=field.getAnnotation(TableId.class);
            if(!ObjectUtils.isEmpty(deField)) {
                return field;
            }
        }
        return keyField;
    }

    /**
     * 获取实体主键值
     * @param entity
     * @param keyField
     * @return
     */
    public Object getKeyFieldValue(Object entity, Field keyField){

        Object fieldValue;
        try {
            String filename = keyField.getName();
            PropertyDescriptor field = new PropertyDescriptor(filename, entity.getClass());
            Method fieldGetMethod = field.getReadMethod();
            fieldValue = fieldGetMethod.invoke(entity);
        } catch (Exception e) {
            throw new RuntimeException("获取实体主键值发生错误"+e);
        }
        return fieldValue;
    }

}
